﻿using AntdUI;
using BST250301;
using BST250301.Views;
using BST250301TestStand.Models.Helpers;
using CsvHelper.Configuration.Attributes;
using NPOI.HSSF.Record;
using NPOI.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static BST250301TestStand.Models.Utils.PLCConfig;
using static BST250301TestStand.Models.Utils.TCUConfig;

namespace BST250301TestStand.Models.Utils
{
    public class ShowDataRecord
    {
        /// <summary>
        /// 标题名称=记录数据Name
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// App名称
        /// </summary>
        public string AppName { get; set; }
        public string Unit { get; set; }
        public string From { get; set; }
        /// <summary>
        /// 程序发送控制值
        /// </summary>
        public List<double> ListS { get; set; }
        /// <summary>
        /// TCU实际控制值
        /// </summary>
        public List<double> ListC { get; set; }
        /// <summary>
        /// 时间轴(ms,自控制开始)
        /// </summary>
        public List<double> ListX { get; set; }
        /// <summary>
        /// TCU反馈值-压力
        /// </summary>
        public List<double> ListY { get; set; }
        /// <summary>
        /// 标准值
        /// </summary>
        public double DefaultValue { get; set; }
        /// <summary>
        /// ListY平均值
        /// </summary>
        public double ReadValueAVG { get; set; }
    }
    public class RecordReport
    {
        /// <summary>
        /// 记录ID
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 方案名称
        /// </summary>
        public string PlanName { get; set; }
        /// <summary>
        /// 方案子项名称
        /// </summary>
        public string TemplateName { get; set; }

        /// <summary>
        /// 测试项目
        /// </summary>
        public string ProjectName { get; set; }

        /// <summary>
        /// 测试项目ID code
        /// </summary>
        public string ProjectCode { get; set; }
        /// <summary>
        /// 项目扫码SN
        /// </summary>
        public string SN { get; set; }
        /// <summary>
        /// 测试次第
        /// </summary>
        public string Times { get; set; }
        /// <summary>
        /// 记录时间
        /// </summary>
        public DateTime DT { get; set; }
        /// <summary>
        /// 油温
        /// </summary>
        public string OilSet { get; set; }
        /// <summary>
        /// 离合
        /// </summary>
        public string CFStatusSet { get; set; }
        public string CRStatusSet { get; set; }
        public string CPTOStatusSet { get; set; }
        /// <summary>
        /// 主挡位
        /// </summary>
        public string GearM { get; set; }
        /// <summary>
        /// 附挡位
        /// </summary>
        public string GearS { get; set; }
        /// <summary>
        /// PTO挡位
        /// </summary>
        public string GearPTO { get; set; }
        /// <summary>
        /// 驱动速度
        /// </summary>
        public int DriverSpeed { get; set; }
        /// <summary>
        /// 项目描述
        /// </summary>
        public string Desc { get; set; }
        /// <summary>
        /// 结果值
        /// </summary>
        public List<RecordData> ListRecord { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Note { get; set; }
        /// <summary>
        /// 存储的路径
        /// </summary>
        public string FilePath { get; set; }
        /// <summary>
        /// 参数名称
        /// </summary>
        public string ReadName { get; set; }
        /// <summary>
        /// 参数报告名称
        /// </summary>
        public string ReadReportName { get; set; }
        /// <summary>
        /// 默认值//理论值
        /// </summary>
        [Name("标准值")]
        public string DefaultValue { get; set; }
        /// <summary>
        /// 标准值-最大
        /// </summary>
        public float StandardMax { get; set; }
        /// <summary>
        /// 标准值-最小
        /// </summary>
        public float StandardMin { get; set; }
        /// <summary>
        /// 设置值
        /// </summary>
        [Name("设置值")]
        public string SetValue { get; set; }
        /// <summary>
        /// 读取值
        /// </summary>
        [Name("读取值")]
        public string ReadValue { get; set; }
        /// <summary>
        /// 平均值
        /// </summary>
        [Name("平均值")]
        public float ReadAVG { get; set; }
        /// <summary>
        /// 最大值
        /// </summary>
        [Name("最大值")]
        public float ReadMax { get; set; }
        /// <summary>
        /// 最小值
        /// </summary>
        [Name("最小值")]
        public float ReadMin { get; set; }
        /// <summary>
        /// 累加值
        /// </summary>
        [Name("计算总合")]
        public float ReadSum { get; set; }
        /// <summary>
        /// 累计次数
        /// </summary>
        [Name("记录数量")]
        public float ReadCount { get; set; }
        /// <summary>
        /// 单位
        /// </summary>
        [Name("单位")]
        public string Unit { get; set; }
        /// <summary>
        /// 合格标志
        /// </summary>
        [Name("合格标志")]
        public string QC { get; set; }
    }
    /// <summary>
    /// 记录数据
    /// </summary>
    public class RecordData
    {
        /// <summary>
        /// 数据ID
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 方案name
        /// </summary>
        [Name("方案名")]
        public string PlanName { get; set; }
        /// <summary>
        /// 方案ID
        /// </summary>
        [Name("方案ID")]
        public string PlanID { get; set; }
        /// <summary>
        /// 子项名称
        /// </summary>
        [Name("子方案名")]
        public string SubPlanName { get; set; }
        /// <summary>
        /// 参数名称
        /// </summary>
        [Name("参数名")]
        public string Name { get; set; }
        /// <summary>
        /// 在程序事件ShowPLC/TCUStatusParm中对应的名称
        /// </summary>
        [Name("参数appname")]
        public string AppName { get; set; }
        /// <summary>
        /// 代号，报告中的名称
        /// </summary>
        [Name("参数名称")]
        public string ReportName { get; set; }
        /// <summary>
        /// 项目名称
        /// </summary>
        [Name("项目名")]
        public string ProjectName { get; set; }
        /// <summary>
        /// 项目ID
        /// </summary>
        [Name("项目ID")]
        public string ProjectID { get; set; }
        /// <summary>
        /// 项目描述
        /// </summary>
        [Name("项目描述")]
        public string ProjectDesc { get; set; }
        /// <summary>
        /// 产品SN
        /// </summary>
        [Name("产品SN")]
        public string ProductSN { get; set; }
        [Name("测试次第")]
        public string ProductTimes { get; set; }
        [Name("日期时间")]
        public DateTime ProjectDT { get; set; }
        /// <summary>
        /// 描述
        /// </summary>
        [Name("参数描述")]
        public string Desc { get; set; }
        /// <summary>
        /// 是否系统固定参数，1为固定
        /// </summary>
        [Name("系统")]
        public bool IsSystemData { get; set; }

        /// <summary>
        /// 数据来源
        /// TCU = 0,PLC = 1,NVH = 2,PC = 3,USER = 4,
        /// </summary>
        [Name("来源")]
        public RecordFrom DataFrom { get; set; }
        /// <summary>
        /// 数据地址
        /// </summary>
        [Name("地址")]
        public string DataAddr { get; set; }
        /// <summary>
        /// 0可读，1可读可写，2可写
        /// </summary>
        [Name("读写")]
        public RecordRW DataRW { get; set; }
        /// <summary>
        /// 数据类型
        /// </summary>
        [Name("类型")]
        public string DataType { get; set; }
        /// <summary>
        /// 数据格式
        /// 计次 = 0,计时 = 1,区间/过程 = 2,开始 = 3,结束 = 4,
        /// </summary>
        [Name("风格")]
        public RecordStyle DataStyle { get; set; }
        /// <summary>
        /// 默认值//理论值
        /// </summary>
        [Name("标准值")]
        public string DefaultValue { get; set; }
        /// <summary>
        /// 标准值-最大
        /// </summary>
        public float StandardMax { get; set; }
        /// <summary>
        /// 标准值-最小
        /// </summary>
        public float StandardMin { get; set; }
        /// <summary>
        /// 设置值
        /// </summary>
        [Name("设置值")]
        public string SetValue { get; set; }
        /// <summary>
        /// 读取值
        /// </summary>
        [Name("读取值")]
        public string ReadValue { get; set; }
        /// <summary>
        /// 平均值
        /// </summary>
        [Name("平均值")]
        public float ReadAVG { get; set; }
        /// <summary>
        /// 最大值
        /// </summary>
        [Name("最大值")]
        public float ReadMax { get; set; }
        /// <summary>
        /// 最小值
        /// </summary>
        [Name("最小值")]
        public float ReadMin { get; set; }
        /// <summary>
        /// 累加值
        /// </summary>
        [Name("计算总合")]
        public float ReadSum { get; set; }
        /// <summary>
        /// 累计次数
        /// </summary>
        [Name("记录数量")]
        public float ReadCount { get; set; }
        /// <summary>
        /// 单位
        /// </summary>
        [Name("单位")]
        public string Unit { get; set; }
        /// <summary>
        /// 合格标志
        /// </summary>
        [Name("合格标志")]
        public string QC { get; set; }
        /// <summary>
        /// 选中状态
        /// </summary>
        [Name("选中")]
        public bool isChecked { get; set; }
    }

    /// <summary>
    /// 区间/过程 = 2
    /// </summary>
    public enum RecordStyle
    {
        计次 = 0,
        计时 = 1,
        区间 = 2,
        开始 = 3,
        结束 = 4,
    }
    public enum RecordFrom
    {
        TCU = 0,
        PLC = 1,
        NVH = 2,
        PC = 3,
        USER = 4,
    }
    public enum RecordRW
    {
        可读 = 0,
        可读可写 = 1,
        可写 = 2,
    }
    
    public class ProjectRecordReport
    {
        /// <summary>
        /// 记录正在测试的数据
        /// 主要是过程数据
        /// 静态数据放在ShowStataus.SaveUSERRecordData里
        /// </summary>
        public static string SaveDataListRecord(ProjectItem item, string oper, int interval, int times, int alltimes)
        {
            string tcuStr = string.Empty;
            string plcStr = string.Empty;
            Stopwatch sw = new();

            var ShowData = new ShowDataRecord();
            var ShowList = ShowStatus._ShowList;// new List<ShowDataRecord>();
            var CanLogEntries = new List<CanLogEntry>();

            var ListAllCloum = new List<string>();
            var ListAllRecord = new List<string>();

            var ListAllHorizontalCloum = new List<string>();
            var ListAllHorizontalCloumCSV = new List<string>();
            var ListAllHorizontalRecord = new List<string>();
            var ListAllHorizontalFilterRecord = new List<string>();
            var DictionaryAllRecord = new ConcurrentDictionary<string, string>();
            var ListFilter = new List<LowPassFilter>();

            if ( item == null || item.ListRecord == null || item.ListRecord.Count == 0)
                return "";
            foreach (RecordData record in item.ListRecord)
            {
                if (record != null)
                {
                    ListAllCloum.Add(record.AppName);
                    ListAllHorizontalCloumCSV.Add(record.ReportName+" "+record.Unit);
                    ListAllHorizontalCloum.Add(record.ReportName); 
                    DictionaryAllRecord.TryAdd(record.ReportName, record.DefaultValue);
                    ListFilter.Add(new LowPassFilter((double)MainWindow.configapp.FilterAlpha));
                    //稳定压力时间放在阶跃测试里记录
                    ShowList.Add(new ShowDataRecord
                    {
                        Title = record.Name,
                        AppName = record.AppName,
                        Unit = record.Unit,
                        DefaultValue = Convert.ToDouble(record.DefaultValue),
                        ListC = new List<double>(),
                        ListX = new List<double>(),
                        ListY = new List<double>(),
                    });

                }
            }

            var dtdatetime = DateTime.Now;
            var dtstart = dtdatetime.ToString("yyyy-MM-dd-HH-mm-ss-ffff");
            ListAllRecord.Add($"测试项目：{item.Name}          第{times}/{alltimes}次");
            ListAllRecord.Add($"产品SN：{item.SN}");
            ListAllRecord.Add($"测试人：{oper}  测试日期：{dtdatetime.ToString("yyyy-MM-dd HH:mm")}  ");
            ListAllRecord.Add($"数据组,日期,名称,代号,设置值,读取值,单位,备注");

            ListAllHorizontalRecord.Add($"测试项目：{item.Name}          第{times}/{alltimes}次");
            ListAllHorizontalRecord.Add($"产品SN：{item.SN}");
            ListAllHorizontalRecord.Add($"测试人：{oper}  测试日期：{dtdatetime.ToString("yyyy-MM-dd HH:mm")}  ");
            ListAllHorizontalRecord.Add($"日期,时间,{string.Join(",", ListAllHorizontalCloumCSV)},备注");

            ListAllHorizontalFilterRecord.Add($"测试项目：{item.Name}          第{times}/{alltimes}次");
            ListAllHorizontalFilterRecord.Add($"产品SN：{item.SN}");
            ListAllHorizontalFilterRecord.Add($"测试人：{oper}  测试日期：{dtdatetime.ToString("yyyy-MM-dd HH:mm")}  ");
            ListAllHorizontalFilterRecord.Add($"日期,时间,{string.Join(",", ListAllHorizontalCloumCSV)},备注");
            
            int tID = 0;
            sw.Start();

            while (ShowStatus.IsRunning)
            {
                Thread.Sleep(interval);

                tID++;
                try
                {
                    var dttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff");
                    //plc数据
                    if (ShowStatus.DataPLC != null)
                    {
                        Type typePLC = typeof(ShowPLCStatusParm);
                        PropertyInfo[] propertiesPLC = typePLC.GetProperties();
                        foreach (PropertyInfo prop in propertiesPLC)
                        {
                            if (ListAllCloum.Contains(prop.Name))
                            {
                                var rec = item.ListRecord.FirstOrDefault(name => name != null && name.AppName == prop.Name);
                                if (rec == null)
                                    continue;
                                rec.ReadValue = prop.GetValue(ShowStatus.DataPLC)?.ToString().Trim();
                                if (float.TryParse(rec.ReadValue, out float floatValue))
                                {
                                    rec.ReadMax = floatValue > rec.ReadMax ? floatValue : rec.ReadMax;
                                    rec.ReadMin = floatValue < rec.ReadMin ? floatValue : rec.ReadMin;
                                    rec.ReadSum += floatValue;
                                    rec.ReadCount++;
                                    rec.ReadAVG = rec.ReadSum / rec.ReadCount;

                                    if (rec.StandardMax != null && rec.StandardMin != null)
                                    {
                                        if (rec.ReadAVG > rec.StandardMax || rec.ReadAVG < rec.StandardMin)
                                            rec.QC = "";// "不合格";
                                        //else
                                        //    rec.QC = "合格";
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(rec.DefaultValue))
                                    {
                                        //if (rec.ReadValue != rec.DefaultValue)
                                        //    rec.QC = "不合格";// "不合格";
                                        //else
                                        //    rec.QC = "合格";
                                    }
                                }
                                DictionaryAllRecord[rec.ReportName] =rec.ReadValue;//如果键存在则更新，不存在则添加
                                ListAllRecord.Add($"{tID}, {dttime},{rec.Name},{rec.ReportName},{ShowStatus.DataPLC.SetpSetValue},{rec.ReadValue},{rec.Unit},");

                                var show = ShowList.FirstOrDefault(name => name.AppName == prop.Name);
                                if (show != null && double.TryParse(rec.ReadValue, out double val))
                                {
                                    double ms = sw.Elapsed.TotalSeconds;
                                    if (double.TryParse(ShowStatus.DataPLC.SetpSetValue, out double setv))
                                        show.ListC.Add(setv);
                                    else
                                        show.ListC.Add(0);
                                    show.From = "PLC";
                                    show.ListX.Add(ms);
                                    show.ListY.Add(val);
                                }
                            }
                        }
                    }
                    //NVH数据
                    if (ShowStatus.DataNVH != null)
                    {
                        Type typeT = typeof(ShowNVHStatusParm);
                        PropertyInfo[] propertiesT = typeT.GetProperties();
                        foreach (PropertyInfo prop in propertiesT)
                        {
                            if (ListAllCloum.Contains(prop.Name))
                            {
                                var rec = item.ListRecord.FirstOrDefault(name => name != null && name.AppName == prop.Name);
                                if (rec == null)
                                    continue;
                                rec.ReadValue = prop.GetValue(ShowStatus.DataNVH)?.ToString().Trim();
                                if (float.TryParse(rec.ReadValue, out float floatValue))
                                {
                                    rec.ReadMax = floatValue > rec.ReadMax ? floatValue : rec.ReadMax;
                                    rec.ReadMin = floatValue < rec.ReadMin ? floatValue : rec.ReadMin; rec.ReadSum += floatValue;
                                    rec.ReadCount++;
                                    rec.ReadAVG = rec.ReadSum / rec.ReadCount;
                                    if (rec.StandardMax != null && rec.StandardMin != null)
                                    {
                                        if (rec.ReadAVG > rec.StandardMax || rec.ReadAVG < rec.StandardMin)
                                            rec.QC = "";// "不合格";
                                        //else
                                        //    rec.QC = "合格";
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(rec.DefaultValue))
                                    {
                                        //if (rec.ReadValue != rec.DefaultValue)
                                        //    rec.QC = "不合格";// "不合格";
                                        //else
                                        //    rec.QC = "合格";
                                    }
                                }
                                DictionaryAllRecord[rec.ReportName] = rec.ReadValue;//如果键存在则更新，不存在则添加
                                ListAllRecord.Add($"{tID}, {dttime},{rec.Name},{rec.ReportName},,{rec.ReadValue},{rec.Unit},");
                                var show = ShowList.FirstOrDefault(name => name.AppName == prop.Name);
                                if (show != null && double.TryParse(rec.ReadValue, out double val))
                                {
                                    double ms = sw.Elapsed.TotalSeconds;
                                    show.From = "NVH";
                                    show.ListX.Add(ms);
                                    show.ListY.Add(val);
                                    show.ListC.Add(val);
                                }
                            }
                        }
                    }
                    //tcu数据
                    if (ShowStatus.DataTCU != null)
                    {
                        var tcucan = new CanLogEntry
                        {
                            Timestamp = ShowStatus.DataTCU.TimeStamp,
                            BusIndex = "1",
                            CanId = ShowStatus.DataTCU.ID,
                            Direction = ShowStatus.DataTCU.IsRx == "Tx" ? "Tx" : "Rx",
                            FrameType = ShowStatus.DataTCU.IsStand == "false" ? "Remote" : "Data",
                            DataDlc = ShowStatus.DataTCU.DataDlc,
                            DataStr = ShowStatus.DataTCU.DataStr,
                        };
                        CanLogEntries.Add(tcucan);

                        Type typeTCU = typeof(ShowTCUStatusParm);
                        PropertyInfo[] propertiesTCU = typeTCU.GetProperties();
                        foreach (PropertyInfo prop in propertiesTCU)
                        {
                            if (ListAllCloum.Contains(prop.Name))
                            {
                                var rec = item.ListRecord.FirstOrDefault(name => name != null && name.AppName == prop.Name);
                                if (rec == null)
                                    continue;
                                rec.ReadValue = prop.GetValue(ShowStatus.DataTCU)?.ToString().Trim();
                                if (float.TryParse(rec.ReadValue, out float floatValue))
                                {
                                    rec.ReadMax = floatValue > rec.ReadMax ? floatValue : rec.ReadMax;
                                    rec.ReadMin = floatValue < rec.ReadMin ? floatValue : rec.ReadMin; rec.ReadSum += floatValue;
                                    rec.ReadCount++;
                                    rec.ReadAVG = rec.ReadSum / rec.ReadCount;
                                    if (rec.StandardMax != null && rec.StandardMin != null)
                                    {
                                        if (rec.ReadAVG > rec.StandardMax || rec.ReadAVG < rec.StandardMin)
                                            rec.QC = "";// "不合格";
                                        //else
                                        //    rec.QC = "合格";
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(rec.DefaultValue))
                                    {
                                        //if (rec.ReadValue != rec.DefaultValue)
                                        //    rec.QC = "不合格";// "不合格";
                                        //else
                                        //    rec.QC = "合格";
                                    }
                                }

                                DictionaryAllRecord[rec.ReportName] =rec.ReadValue;//如果键存在则更新，不存在则添加
                                ListAllRecord.Add($"{tID}, {dttime},{rec.Name},{rec.ReportName},{ShowStatus.DataTCU.StepSetValue},{rec.ReadValue},{rec.Unit},");
                                var show = ShowList.FirstOrDefault(name => name.AppName == prop.Name);
                                if (show != null && double.TryParse(rec.ReadValue, out double val))
                                {
                                    double ms = sw.Elapsed.TotalSeconds;
                                    show.From = "TCU";
                                    show.ListX.Add(ms);
                                    show.ListY.Add(val);
                                    if (double.TryParse(ShowStatus.DataTCU.StepSetValue, out double setv))
                                        show.ListC.Add(setv);
                                    else
                                        show.ListC.Add(0);
                                }
                            }
                        }
                    }
                    //user数据//User自输入数据       
                    if (ShowStatus.DictionaryUser != null)
                    {
                        foreach (var itemdict in ListAllHorizontalCloum)
                        {
                            if (ShowStatus.DictionaryUser.ContainsKey(itemdict))
                            {                               
                                DictionaryAllRecord[itemdict] = ShowStatus.DictionaryUser[itemdict];//如果键存在则更新，不存在则添加                               
                            }
                        }
                    }
                    string str = string.Empty;

                    //foreach (var cloumitem in ListAllHorizontalCloum)
                    //{
                    //    str+=DictionaryAllRecord[cloumitem]+",";
                    //}
                    //ListAllHorizontalRecord.Add($" {dttime},{sw.Elapsed.TotalSeconds},{str}");

                    string strFilter = string.Empty;

                    for (int i = 0; i < ListAllHorizontalCloum.Count; i++)
                    {
                        var cloumitem = ListAllHorizontalCloum[i];

                        str += DictionaryAllRecord[cloumitem] + ",";
                        var filter = ListFilter[i];
                        string strtemp = Operation.GetLowPassFilterStr(DictionaryAllRecord[cloumitem], filter);

                        strFilter += strtemp + ",";
                    }
                    ListAllHorizontalRecord.Add($" {dttime},{sw.Elapsed.TotalSeconds},{str}");
                    ListAllHorizontalFilterRecord.Add($" {dttime},{sw.Elapsed.TotalSeconds},{strFilter}");
                }
                catch (Exception ex)
                {
                }
            }

            sw.Stop();

            string resultCSV = SaveReportCSVFile(item, ListAllRecord, dtdatetime, dtstart, times, alltimes);
            string resultHorizontalCSV = SaveReportHorizontalCSVFile(item, ListAllHorizontalRecord, dtdatetime, dtstart, times, alltimes);

            string resultHorizontalFilterCSV = SaveReportHorizontalFilterCSVFile(item, ListAllHorizontalFilterRecord, dtdatetime, dtstart, times, alltimes);

            string resultASC = SaveCanLogASCFile(item, CanLogEntries, dtdatetime, dtstart);
            //var resultdb = SaveReportRecord(item, dtdatetime, oper);
            return resultCSV;
        }

        /// <summary>
        /// 保存CSV文件
        /// </summary>
        /// <param name="item"></param>
        /// <param name="ListAllRecord"></param>
        /// <param name="CanLogEntries"></param>
        /// <param name="dtnow"></param>
        /// <param name="dtstart"></param>
        /// <returns>保存的文件名及路径</returns>
        private static string SaveReportCSVFile(ProjectItem item, List<string> ListAllRecord, DateTime dtnow, string dtstart, int times, int alltimes)
        {
            try
            {
                string filepath = $"D:\\Record\\{dtnow.ToString("yyyy")}\\{dtnow.ToString("MM")}\\{dtnow.ToString("dd")}\\";
                string filename = $"{item.Name}_Test_Data_SN{item.SN}_{dtstart}_{times}次.csv";
                if (ListAllRecord != null && ListAllRecord.Count > 0)
                    CSV.SaveProductList2CSV(ListAllRecord, filepath, filename);
                return filepath + filename;
            }
            catch (Exception ex)
            {
                return $"";

                //return $"保存记录错误：{ex.Message}";
            }
        }
        /// <summary>
        /// 保存水平CSV文件
        /// </summary>
        /// <param name="item">获取名称sn等</param>
        /// <param name="ListAllRecord">已排好版的横向数据</param>
        /// <param name="dtnow"></param>
        /// <param name="dtstart"></param>
        /// <param name="times"></param>
        /// <param name="alltimes"></param>
        /// <returns>返回文件名全路径</returns>
        private static string SaveReportHorizontalCSVFile(ProjectItem item, List<string> ListAllRecord, DateTime dtnow, string dtstart, int times, int alltimes)
        {
            try
            {
                string filepath = $"D:\\Record\\{dtnow.ToString("yyyy")}\\{dtnow.ToString("MM")}\\{dtnow.ToString("dd")}\\";
                string filename = $"{item.Name}_Horizontal_Test_Data_SN{item.SN}_{dtstart}_{times}次.csv";
                if (ListAllRecord != null && ListAllRecord.Count > 0)
                    CSV.SaveProductList2CSV(ListAllRecord, filepath, filename);
                return filepath + filename;
            }
            catch (Exception ex)
            {

                return $"保存记录错误：{ex.Message}";
            }
        }
        /// <summary>
        /// 保存水平CSV文件加滤波
        /// </summary>
        /// <param name="item">获取名称sn等</param>
        /// <param name="ListAllRecord">已排好版的横向数据</param>
        /// <param name="dtnow"></param>
        /// <param name="dtstart"></param>
        /// <param name="times"></param>
        /// <param name="alltimes"></param>
        /// <returns>返回文件名全路径</returns>
        private static string SaveReportHorizontalFilterCSVFile(ProjectItem item, List<string> ListAllRecord, DateTime dtnow, string dtstart, int times, int alltimes)
        {
            try
            {
                string filepath = $"D:\\Record滤波数据\\{dtnow.ToString("yyyy")}\\{dtnow.ToString("MM")}\\{dtnow.ToString("dd")}\\";
                string filename = $"{item.Name}_Test_LowPassFilterData_Horizontal_SN_{item.SN}_{dtstart}_{times}次.csv";
                if (ListAllRecord != null && ListAllRecord.Count > 0)
                    CSV.SaveProductList2CSV(ListAllRecord, filepath, filename);
                return filepath + filename;
            }
            catch (Exception ex)
            {

                return $"保存记录错误：{ex.Message}";
            }
        }
        /// <summary>
        /// 保存CAN日志文件
        /// </summary>
        /// <param name="item"></param>
        /// <param name="ListAllRecord"></param>
        /// <param name="CanLogEntries"></param>
        /// <param name="dtnow"></param>
        /// <param name="dtstart"></param>
        /// <returns>保存的文件名及路径</returns>
        private static string SaveCanLogASCFile(ProjectItem item, List<CanLogEntry> CanLogEntries, DateTime dtnow, string dtstart)
        {
            try
            {
                string filepath = $"D:\\Record\\{dtnow.ToString("yyyy")}\\{dtnow.ToString("MM")}\\{dtnow.ToString("dd")}\\";
                string canlogfilefullname = filepath + $"TCU_CanLog_{item.Name}_Data_SN{item.SN}_{dtstart}.asc";
                if (CanLogEntries != null && CanLogEntries.Count > 0)
                    CanLogGenerator.WriteToFile(canlogfilefullname, CanLogEntries);
                return canlogfilefullname;
            }
            catch (Exception ex)
            {

                return $"保存记录错误：{ex.Message}";
            }
        }
        /// <summary>
        /// 保存到数据库报告记录
        /// </summary>
        /// <param name="projectitem"></param>
        /// <param name="dtnow"></param>
        /// <param name="oper"></param>
        /// <returns>保存是否成功</returns>
        public static bool SaveReportRecord(ProjectItem projectitem, DateTime dtnow, string oper, int times)
        {
            try
            {
                var recorditem = new RecordReport
                {
                    PlanName = projectitem.PlanName,
                    TemplateName = projectitem.TemplateName,
                    ProjectName = projectitem.Name,
                    ProjectCode = projectitem.Code,
                    OilSet = projectitem.TemperatureOil.ToString(),
                    CFStatusSet = projectitem.CFStatus.ToString(),
                    CRStatusSet = projectitem.CRStatus.ToString(),
                    CPTOStatusSet = projectitem.CPTOStatus.ToString(),
                    DriverSpeed = projectitem.RotateSpeed.ValueStart,
                    GearM = projectitem.MasterGearPosition.ToString(),
                    GearS = projectitem.SlaveGearPosition.ToString(),
                    GearPTO = projectitem.PTOGearPosition.ToString(),
                    Desc = projectitem.Description,
                    Note = projectitem.Note,
                    ListRecord = projectitem.ListRecord,
                    QC =projectitem.IsItemOKNG? "合格" : "",

                };
                bool ret = false;
                foreach (var item in recorditem.ListRecord)
                {
                    if (item == null)
                        continue;
                    //(string testprojectid, string sn, string dataname, string datadesc, string datatype, string defaultvalue, string readavg, string readmax, string readmin)
                    //if (string.IsNullOrEmpty(item.QC))
                    //    item.QC = "合格/不合格";
                    ret = DB.SaveResultParameters(oper, recorditem.PlanName, recorditem.TemplateName, recorditem.ProjectCode, recorditem.ProjectName, projectitem.SN, times.ToString(), dtnow, item.Name, item.Desc, item.DataType, item.DefaultValue, item.ReadValue, item.ReadAVG.ToString("F2"), item.ReadMax.ToString("F2"), item.ReadMin.ToString("F2"), item.QC, item.Unit);
                }
                return ret;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"错误：{ex.Message}");
            }
            return false;
        }
    }
}
